package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.common.pojo.Employee;
import com.itheima.exception.TokenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liguoping
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
//    @Autowired
//    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            throw new TokenException();
        }
//        Employee employee = employeeMapper.getByToken(token);
        String employee = (String) redisTemplate.opsForValue().get("employee_token:" + token);
        Employee emp = JSON.parseObject(employee, Employee.class);
        if (emp == null) {
            throw new TokenException();
        }
        return true;
    }
}
